var mysql = require('mysql')
const pool = mysql.createPool({
  host: '43.138.154.74',
  user: 'demo-cg' /* 用户名 */,
  password: '123456',
  database: 'demo-cg' /* 数据库名 */,
})

// sql 语句， values ： 参数
function query(sql, values, type = 'array') {
  return new Promise((resolve, reject) => {
    pool.getConnection((err, connection) => {
      if (connection === undefined) {
        return reject({
          msg: "网络出小差啦(●'◡'●)",
        })
      }

      if (err) reject(err)

      connection.query(sql, values, (err, rows) => {
        console.log(err);
        if (err) reject(err)

        if (type === 'object') resolve(rows[0] || {})
        else resolve(rows)

        connection.release()
      })
    })
  })
}

module.exports = query
